﻿using Common;
using Common.EF.Controllers;
using Common.Model;
using Common.Models;
using Common.Utility;
using Common.Utility.AJ;
using Common.Utility.AJ.MobileConfiguration;
using Common.Utility.AJ.MobileConfiguration.WeightSystem;
using FluentValidation;
using Masuit.Tools;
using Masuit.Tools.Core.Validator;
using Masuit.Tools.Reflection;
using Microsoft.EntityFrameworkCore;
using NPOI.SS.Formula.Functions;
using Stylet;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using Yitter.IdGenerator;

namespace AWSV2.ViewModels
{
    public class WeighingRecordRelationDetailViewModel : AnnotationValidationScreen<WeighingRecordRelation>
    {

        private static readonly string[] _ignoreFields = WeighingRecord.GetPoundIgnoreFields();

        private string _title;
        public string Title
        {
            get => _title;
            set => SetAndNotify(ref _title, value);
        }

        private AJErrorInfoDialogParams _errorInfo;
        public AJErrorInfoDialogParams ErrorInfo
        {
            get => _errorInfo;
            set => SetAndNotify(ref _errorInfo, value);
        }

        private bool _addMode;
        public bool AddMode
        {
            get => _addMode;
            set => SetAndNotify(ref _addMode, value);
        }

        private bool _loading;
        public bool Loading
        {
            get => _loading;
            set => SetAndNotify(ref _loading, value);
        }

        private WeighingRecordRelation _form;
        public override WeighingRecordRelation Form
        {
            get => _form;
            set => SetAndNotify(ref _form, value);
        }

        private BindableCollection<WeighingRecordRelation> _rows;
        public BindableCollection<WeighingRecordRelation> Rows
        {
            get
            {
                return _rows;
            }
            set
            {
                SetAndNotify(ref _rows, value);
            }

        }

        private WeighingRecordRelation _current;
        public WeighingRecordRelation Current
        {
            get => _current;
            set => SetAndNotify(ref _current, value);
        }

        private BindableCollection<DynamicPoundFieldItem> _propertyOptions;
        public BindableCollection<DynamicPoundFieldItem> PropertyOptions
        {
            get
            {
                return _propertyOptions;
            }
            set
            {
                SetAndNotify(ref _propertyOptions, value);
            }

        }

        public WeighingRecordRelationDetailViewModel(WeighingRecordRelation form = null)
        {
            ErrorInfo = new AJErrorInfoDialogParams();

            AddMode = form == null;
            Title = AddMode
                ? I18NService.Translate(LangKeys.新增关联)
                : I18NService.Translate(LangKeys.编辑_0_, form.DisplayName);
            _form = new WeighingRecordRelation();
            if (form != null)
            {
                AJUtil.CopyPropertyValues(_form, form);
            }
            Rows = new BindableCollection<WeighingRecordRelation>();
        }

        protected override async void OnViewLoaded()
        {
            Loading = true;

            var pound = new PoundCfg();

            var mgr = new MobileConfigurationMgr(true)
            {
                WeightFormTemplatePath = Globalspace._weightFormTemplatePath
            };

            var _fieldsSource = await pound.InitFieldsAsync(mgr, true);

            var allDyanmicPoundFieldItems = Common.Models.WeighingRecord
                .GetDyanmicPoundFieldItems(Common.Utility.SettingsHelper.AWSV2Settings, true, false)
                .Where(p => !_ignoreFields.Contains(p.Field) && p.IsFormDisplay).ToList();

            PropertyOptions = new BindableCollection<DynamicPoundFieldItem>(allDyanmicPoundFieldItems);

            Loading = false;

            Rows.AddRange(_form.Children);
            CanCommit = ComputeCanCommit();
        }

        private bool ComputeCanCommit()
        {
            return !string.IsNullOrWhiteSpace(_form.PropertyName)
                && !string.IsNullOrWhiteSpace(_form.PropertyValue)
                && Rows.Count > 0;
        }

        private bool _canCommit;
        public bool CanCommit
        {
            get
            {
                _canCommit = !Loading && ComputeCanCommit();
                return _canCommit;
            }
            set => SetAndNotify(ref _canCommit, value);
        }


        public async void Commit()
        {
            if (!ValidateModel())
            {
                ErrorInfo.Show(string.Join("\r\n", ValidationErrorsByProperty.SelectMany(p => p.Value).Select(p => p.ToString())));
                return;
            }

            _form.DisplayName = PropertyOptions.FirstOrDefault(p => p.Field == _form.PropertyName)?.Label;

            // 主字段不允许添加车号，会导致一些问题，--阿吉 2024年12月20日16点26分
            if (_form.PropertyName == nameof(WeighingRecord.Ch))
            {
                ErrorInfo.Show(I18NService.Translate(LangKeys._0_不允许设置关联, _form.DisplayName));
                return;
            }

            _form.Children = Rows.ToList();

            _form.Children.ForEach(i =>
            {
                i.DisplayName = PropertyOptions.FirstOrDefault(p => p.Field == i.PropertyName)?.Label;
            });

            Loading = true;
            try
            {
                using var ctrl = new WeighingRecordRelationController();
                var result = await ctrl.Save(AJAutoMapperService.Instance()
                    .Mapper.Map<WeighingRecordRelation, Common.EF.Tables.WeighingRecordRelation>(_form));

                RequestClose(true);
            }
            catch (Exception e)
            {
                ErrorInfo.Show(e.Message);
            }
            finally
            {
                Loading = false;
            }
        }

        public void Add()
        {
            var first = PropertyOptions.Where(p => !Rows.Select(q => q.PropertyName).Contains(p.Field)).FirstOrDefault();

            Rows.Add(new WeighingRecordRelation
            {
                Id = YitIdHelper.NextId(),
                PropertyValue = $"{I18NService.Translate(LangKeys.字段值)}_{Form.Children.Count + 1}",
                PropertyName = first?.Field,
                DisplayName = first?.Label
            });
            CanCommit = ComputeCanCommit();
        }

        #region 行选择功能 --阿吉 2024年4月25日10点43分

        private CheckBox _allRowCheckbox;
        private bool _allRowCheckboxProcess;

        private bool _canDeleteSelected;
        public bool CanDeleteSelected
        {
            get
            {
                _canDeleteSelected = Rows.Any(p => p.Checked);
                return _canDeleteSelected;
            }
            set { SetAndNotify(ref _canDeleteSelected, value); }
        }


        public void DeleteSelected()
        {
            var selected = Rows.Where(p => p.Checked).ToList();

            if (MessageBox.Show(I18NService.Translate(LangKeys.确认删除_0_条数据吗, selected.Count), I18NService.Translate(LangKeys.提示), MessageBoxButton.OKCancel)
                == MessageBoxResult.OK)
            {
                Rows.RemoveRange(selected);
                CanCommit = Rows.Count > 0;
            }
        }

        public void RowCheckedChangedHandle(object sender, System.Windows.RoutedEventArgs e)
        {
            if (_allRowCheckboxProcess)
            {
                return;
            }
            var cbx = ((CheckBox)sender);
            var view = cbx.DataContext as WeighingRecordRelation;
            if (view == null)
            {
                return;
            }
            view.Checked = cbx.IsChecked.GetValueOrDefault();

            var checkedCount = 0;

            foreach (var row in Rows)
            {
                if (row.Checked)
                {
                    checkedCount++;
                }
            }

            _allRowCheckbox.IsThreeState = checkedCount > 0 && checkedCount != Rows.Count;
            if (_allRowCheckbox.IsThreeState)
            {
                _allRowCheckbox.IsChecked = null;
            }
            else
            {
                _allRowCheckbox.IsChecked = checkedCount == Rows.Count;
            }
            CanDeleteSelected = Rows.Any(p => p.Checked);
        }


        public void AllRowCheckBox_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            _allRowCheckbox = (CheckBox)sender;
        }

        public void AllRowCheckedChangedHandle(object sender, System.Windows.RoutedEventArgs e)
        {
            _allRowCheckboxProcess = true;
            var cbx = ((CheckBox)sender);
            cbx.IsThreeState = !cbx.IsChecked.HasValue;
            if (cbx.IsChecked != null && cbx.IsChecked.HasValue)
            {
                foreach (var row in Rows)
                {
                    row.Checked = cbx.IsChecked.GetValueOrDefault();
                }
            }
            _allRowCheckboxProcess = false;
            CanDeleteSelected = Rows.Any(p => p.Checked);
        }



        #endregion
    }
}
